﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YiSha.Data.Repository;
using YiSha.Entity.SystemManage;
using YiSha.Enums;
using YiSha.Enums.SystemManage;
using YiSha.Model.Param.SystemManage;
using YiSha.Util;
using YiSha.Util.Model;
using YiSha.Business.Cache;
using YiSah.Entity.Extension.Systen;
using System;
using YiSha.Model;
using YiSha.Model.Extension.Systen;
using YiSha.SqlSugars;

namespace YiSha.Service.SystemManage
{
    public class RoleService : RepositoryFactory
    {
        private MenuAuthorizeService menuAuthorizeService = new MenuAuthorizeService();

        private MenuAuthorizeCache menuAuthorizeCache = new MenuAuthorizeCache();

        #region 获取数据
        public async Task<TData<List<RoleEntityExtension>>> GetList(RoleListParam param)
        {
            TData<List<RoleEntityExtension>> obj = new TData<List<RoleEntityExtension>>()
            {
                Data = new List<RoleEntityExtension>()
            };
            var expression = ExtLinq.True<RoleEntity>();
            if (!param.RoleName.IsEmpty())
            {
                expression = expression.And(t => t.RoleName.Contains(param.RoleName));
            }
            if (!param.RoleIds.IsEmpty())
            {
                var roleIdArr = TextHelper.SplitToArray<string>(param.RoleIds, ',');
                expression = expression.And(t => roleIdArr.Contains(t.Id));
            }
            if (!param.RoleStatus.IsEmpty())
            {
                expression = expression.And(t => t.RoleStatus == param.RoleStatus);
            }
            var list = SqlSugarAdapters.GetList(expression);
            list.ForEach(f =>
            {
                var map = DictionaryMapUtils.Mapping<RoleEntityExtension, RoleEntity>(f);
                obj.Data.Add(map);
            });
            obj.Total = obj.Data.Count;
            return obj;
        }

        public async Task<TData<List<RoleEntityExtension>>> GetPageList(RoleListParam param, Pagination pag)
        {
            TData<List<RoleEntityExtension>> obj = new TData<List<RoleEntityExtension>>();
            var expression = ExtLinq.True<RoleEntityExtension>();
            if (!param.RoleName.IsEmpty())
            {
                expression = expression.And(t => t.RoleName.Contains(param.RoleName));
            }
            if (!param.RoleIds.IsEmpty())
            {
                var roleIdArr = TextHelper.SplitToArray<string>(param.RoleIds, ',');
                expression = expression.And(t => roleIdArr.Contains(t.Id));
            }
            if (!param.RoleStatus.IsEmpty())
            {
                expression = expression.And(t => t.RoleStatus == param.RoleStatus);
            }
            var list = SqlSugarAdapters.GetPager(expression, pag);
            var roleMenu = SqlSugarAdapters.GetList<MenuAuthorizeEntityExt>();
            list.Item2.ToList().ForEach(f =>
            {
                var menu = roleMenu.Where(w => w.AuthorizeId == f.Id).ToList();
                f.MenuIds = string.Join(",", menu.Select(s => s.MenuId));
            });
            obj.Data = list.Item2;
            obj.Total = list.Item1;
            return obj;
        }

        public async Task<TData<RoleEntityExtension>> GetEntity(string id)
        {
            TData<RoleEntityExtension> obj = new TData<RoleEntityExtension>();
            var roleEntity = SqlSugarAdapters.GetEntity<RoleEntityExtension>(s => s.Id == id);
            List<MenuAuthorizeEntityExt> menuAuthorizeList = await menuAuthorizeService.GetList(new MenuAuthorizeEntityExt
            {
                AuthorizeId = id,
                AuthorizeType = AuthorizeTypeEnum.Role.ParseToInt()
            });
            // 获取角色对应的权限
            roleEntity.MenuIds = string.Join(",", menuAuthorizeList.Select(p => p.MenuId));

            obj.Data = roleEntity;
            return obj;
        }

        public async Task<TData<int>> GetMaxSort()
        {
            TData<int> obj = new TData<int>();
            var result = SqlSugarAdapters.SqlQueryCount("SELECT MAX(RoleSort) FROM SysRole");
            int sort = result.ParseToInt();
            sort++;
            obj.Data = sort;
            return obj;
        }
        #endregion

        #region 提交数据
        public async Task<TData<string>> SaveForm(RoleEntityExtension entity)
        {
            TData<string> obj = new TData<string>();
            using (var db = SugarBase.GetInstance())
            {
                try
                {
                    if (ExistRoleName(entity))
                    {
                        obj.MsgCode = MsgCode.Fail;
                        obj.Msg = "角色名称已经存在！";
                        return obj;
                    }
                    var result = db.UseTran(() =>
                    {
                        if (entity.Id.IsEmpty())
                        {
                            entity.Create();
                            db.Insertable(entity).ExecuteCommand();
                        }
                        else
                        {
                            db.Deleteable<MenuAuthorizeEntity>(t => t.AuthorizeId == entity.Id).ExecuteCommand();
                            entity.Modify();
                            db.Updateable(entity).ExecuteCommand();
                        }
                        // 角色对应的菜单、页面和按钮权限
                        if (!string.IsNullOrEmpty(entity.MenuIds))
                        {
                            var menus = new List<MenuAuthorizeEntity>();
                            TextHelper.SplitToArray<string>(entity.MenuIds, ',').ToList().ForEach(f =>
                            {
                                MenuAuthorizeEntity menuAuthorizeEntity = new MenuAuthorizeEntity();
                                menuAuthorizeEntity.AuthorizeId = entity.Id;
                                menuAuthorizeEntity.MenuId = f;
                                menuAuthorizeEntity.AuthorizeType = AuthorizeTypeEnum.Role.ParseToInt();
                                menuAuthorizeEntity.Create();
                                menus.Add(menuAuthorizeEntity);
                            });
                            db.Insertable(menus).ExecuteCommand();
                        }
                    });
                    if (result.IsSuccess)
                    {
                        // 清除缓存里面的权限数据
                        menuAuthorizeCache.Remove();
                        return obj;
                    }
                    obj.Msg = "操作失败，请稍后再试";
                    obj.MsgCode = MsgCode.Fail;
                    return obj;
                }
                catch (Exception ex)
                {
                    obj.MsgCode = MsgCode.Fail;
                    obj.Msg = ex.Message;
                    return obj;
                }
            }
        }
        public bool ExistRoleName(RoleEntity entity)
        {
            var expression = ExtLinq.True<RoleEntity>();
            expression = expression.And(t => t.Valid);
            if (entity.Id.IsEmpty())
            {
                expression = expression.And(t => t.RoleName == entity.RoleName);
            }
            else
            {
                expression = expression.And(t => t.RoleName == entity.RoleName && t.Id != entity.Id);
            }
            return this.BaseRepository().IQueryable(expression).Count() > 0 ? true : false;
        }
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<TData> ChangeStatus(string ids)
        {
            TData obj = new TData();
            var info = SqlSugarAdapters.GetEntity<RoleEntity>(s => s.Id == ids);
            if (!info.IsEmpty())
            {
                info.RoleStatus = info.RoleStatus == 1 ? 0 : 1;
                SqlSugarAdapters.UpdateColumns<RoleEntity>(info, it => new { it.RoleStatus });
            }
            else
            {
                obj.MsgCode = MsgCode.Fail;
                obj.Msg = "当前数据不存在";
            }
            // 清除缓存里面的权限数据
            menuAuthorizeCache.Remove();

            return obj;
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<TData> DeleteForm(List<string> ids)
        {
            TData obj = new TData();

            var info = SqlSugarAdapters.GetList<RoleEntity>(s => ids.Contains(s.Id));
            if (info.Count > 0)
            {
                SqlSugarAdapters.Delete<RoleEntity>(s => ids.Contains(s.Id));
            }
            else
            {
                obj.MsgCode = MsgCode.Fail;
                obj.Msg = "当前数据不存在";
            }
            SqlSugarAdapters.Delete<RoleEntity>(s => ids.Contains(s.Id));
            // 清除缓存里面的权限数据
            menuAuthorizeCache.Remove();

            return obj;
        }
        #endregion

    }
}
